package com.jincp.image.compress;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 压缩照片,采用luban
 * Author: crazycodeboy
 * Date: 2016/11/5 0007 20:10
 * Version:4.0.0
 * 技术博文：http://www.devio.org/
 * GitHub:https://github.com/crazycodeboy
 * Email:crazycodeboy@gmail.com
 */
public class ImageCompressWithJPEG extends ImageCompress {

    static {
        try {
            System.loadLibrary("jpegbither");
            System.loadLibrary("mylibjpeg");
        } catch (UnsatisfiedLinkError error) {
            error.printStackTrace();
        }
    }

    private static Context mContext;
    private File compressFile;
    private List<String> compressImagePathList;

    //返回值"1"是成功，"0"是失败
    private static native String compressBitmap(Bitmap bitmap, int width, int height, int quality, byte[] fileNameBytes,
                                                boolean optimize);

    @Override
    public void init(Context context) {
        mContext = context.getApplicationContext();
        initCompressFile();
    }

    public void initCompressFile() {
        /**
         * 如果存在SD卡则将缓存写入SD卡,否则写入手机内存
         */
        try {
            File cacheDirectory = null;
            if (mContext.getExternalCacheDir() != null &&
                    Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                cacheDirectory = mContext.getExternalCacheDir().getCanonicalFile();
            } else {
                cacheDirectory = mContext.getCacheDir().getCanonicalFile();
            }
            compressFile = new File(cacheDirectory, "compress");
            if (!compressFile.exists()) {
                compressFile.mkdirs();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void compressImage(List<String> imagePathList, int quality, ImageCompressListener listener) {
        compressImagePathList = new ArrayList<>();
        if (imagePathList.size() == 1) {
            compressOne(imagePathList.get(0), quality);
        } else {
            compressMulti(imagePathList, quality);
        }
        Log.d("ImageCompressWithJPEG", "Compress success");
        if (listener != null) {
            listener.onCompressCompleted(compressImagePathList);
        }
    }

    private void compressMulti(List<String> imagePathList, int quality) {
        for (String imagePath : imagePathList) {
            compressOne(imagePath, quality);
        }
    }

    private void compressOne(String imagePath, int quality) {
        if (TextUtils.isEmpty(imagePath)){
            return;
        }
        File imageFile = new File(imagePath);
        if (!imageFile.exists()){
            return;
        }
        String fileName = imageFile.getName();
        File newCompressFile = new File(compressFile, fileName);
        if (newCompressFile.exists()) newCompressFile.delete();
        Bitmap bitmap = null;
        try {
            bitmap = decodeBitmapFromFile(imagePath);
            Log.d("ImageCompressWithJPEG", "imageFile.size = " + getFileSize(imageFile.length()));
            String savePath = newCompressFile.getAbsolutePath();
            if ("1".equals(compressBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), quality, savePath.getBytes(), true))){
                File newFile = new File(savePath);
                Log.d("ImageCompressWithJPEG", "imageFile.size = " + getFileSize(newFile.length()));
                compressImagePathList.add(savePath);
            } else {
                compressImagePathList.add(imagePath);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if(bitmap != null){
                bitmap.recycle();
            }
        }
    }

}
